package com.czuft.usersystem.controller;

import com.czuft.usersystem.component.PathComponent;
import com.czuft.usersystem.config.MyWebAppConfigurer;
import com.czuft.usersystem.dao.Result;
import com.czuft.usersystem.dao.VueResult;
import com.czuft.usersystem.pojo.*;
import com.czuft.usersystem.service.*;
import com.czuft.usersystem.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;


@Controller
@Slf4j
@RequestMapping({"/usersystem"})
@Scope("prototype")
// 多例模式防止 Vector<FoundationMt3> VusersystemMt3List 数据乱串 https://blog.csdn.net/qianjingfan/article/details/105753331
public class UserSystemController {

    // token
    @Resource()
    TokenUtil tokenUtil;

    @Resource
    PathComponent pathComponent;

    // 用户
    @Resource()
    private UserService userService;

    //  文件
    @Resource()
    private FileService fileService;
    @Resource()
    private MyWebAppConfigurer config;

    // 用户登录后自动跳转到用户模块
    @RequestMapping({"/login"})
    @ResponseBody
    public VueResult<Object> login(User user,
                                               HttpServletResponse res,
                                               HttpSession session) throws Exception {
        Map<String, Object> map = userService.login(user);
        VueResult<Object> result = new VueResult<>();

        if (map.size() == 0) {
            result.setResult("-1");
            result.setMessage("账号密码有误");
            result.setList(null);
            result.setToken("");
            result.setUser(null);
            return result;
        }
        User reuser=null;
        for (Map.Entry<String, Object> one : map.entrySet()) {
            if (one.getKey().equals("user")) {
                reuser = (User) one.getValue();
                session.setAttribute("name", reuser.getName());
            }
        }
        result.setResult("0");
        result.setMessage("登录成功");
        result.setUser(reuser);
        //解决办法就是加上这一行代码，跨域访问允许访问的响应头的内容
        res.setHeader("Access-Control-Expose-Headers", "token");
        String token = tokenUtil.getToken(user.getName());
        res.setHeader("token", token);
        result.setToken(token);

        return result;

    }

    @RequestMapping({"/getUsersById"})
    @ResponseBody
    public List<User> getUsersById(long id) throws Exception {
        User user = new User();
        List<User> list = new ArrayList<>();
        user = userService.getUserById(id);
        list.add(user);
        return list;

    }
    @RequestMapping({"/getUsersByName"})
    @ResponseBody
    public List<User> getUsersByName(String name) throws Exception {
        User user = new User();
        user.setName(name);
        List<User> list;
        if (user.getName() != null && !user.getName().equals("")) {
            list = userService.getUserlistByName(user);
        } else {
            list = userService.getUserlistAll();
        }

        if (list == null) {
            list = new ArrayList<>();
        }

        List<User> listObject = new ArrayList<>();
        for (User value : list) {
            user = new User();
            user.setUserimg(value.getUserimg());
            user.setId(value.getId());
            user.setName(value.getName());
            user.setPassword(value.getPassword());
            user.setEmail(value.getEmail());
            user.setPhonenumber(value.getPhonenumber());
            listObject.add(user);
        }
        return listObject;

    }

    @RequestMapping({"/getUsers"})
    @ResponseBody
    public List<User> getUsers(String name, Integer start,
                               Integer pageSize) throws Exception {
        User user = new User();
        user.setName(name);
        List<User> list;
        if (user.getName() != null && !user.getName().equals("")) {
            list = userService.getUserlistByName(user);
        } else {
            list = userService.getUserlistAll();
        }

        int endIndex = start + pageSize;

        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.size() < endIndex) {
            endIndex = list.size();
        }
        List<User> listObject = new ArrayList<>();
        for (int i = start; i < endIndex; i++) {
            user = new User();
            user.setUserimg(list.get(i).getUserimg());
            user.setId(list.get(i).getId());
            user.setName(list.get(i).getName());
            user.setEmail(list.get(i).getEmail());
            user.setPassword(list.get(i).getPassword());
            user.setPhonenumber(list.get(i).getPhonenumber());
            listObject.add(user);
        }
        return listObject;

    }

    @RequestMapping({"/getUsersTotal"})
    @ResponseBody
    public Integer getUsersTotal(User user) throws Exception {
        List<User> users = userService.getUserlistByName(user);
        if (users != null) {
            return users.size();
        } else {
            return 0;
        }
    }

    @RequestMapping({"/addSaveUserData"})
    @ResponseBody
    public Result addSaveUserData(User user) throws Exception {

        Result result = new Result();

        if (userService.selectByName(user)) {
            user = userService.insert(user);
            if (user != null) {
                result.setResult("0");
                result.setMessage("操作完成");
                result.setImgUrl(user.getUserimg());
            } else {
                result.setResult("-1");
                result.setMessage("操作失败");
                result.setImgUrl("");
            }
        } else {
            result.setResult("-1");
            result.setMessage("操作失败");
            result.setImgUrl("");
        }
        return result;
    }

    // 用户信息修改完成
    @RequestMapping({"/updateSaveUserData"})
    @ResponseBody
    public Result updateSaveUserData(User newuser) throws Exception {
        User user = userService.getUserById(newuser.getId());
        // 删除原来的图片
        if (user.getUserimg() != null
                && !(user.getUserimg().equals(""))
                && !(newuser.getUserimg().equals(user.getUserimg()))) {
            String filePath = config.ROOT_PATH + user.getUserimg();
            fileService.deleteFile(filePath);
        }
        //修改信息
        user.setUserimg(newuser.getUserimg());
        user.setName(newuser.getName());
        user.setPassword(newuser.getPassword());
        user.setEmail(newuser.getEmail());
        user.setPhonenumber(newuser.getPhonenumber());
        Result result = new Result();
        user = userService.update(user);
        if (user != null) {
            result.setResult("0");
            result.setMessage("操作完成");
            result.setImgUrl(user.getUserimg());
        } else {
            result.setResult("-1");
            result.setMessage("操作失败");
            result.setImgUrl("");
        }
        return result;
    }


    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(User user) throws Exception {
        // 当前用户
        user = userService.getUserById(user.getId());
        String imgName;
        if (user.getUserimg() != null && !(user.getUserimg().equals(""))) {
            imgName = user.getUserimg().replaceFirst(config.uploadPath, "");
            String filePath = config.ROOT_PATH + imgName;
            fileService.deleteFile(filePath);
        }
        Result result = new Result();
        userService.deleteUserById(user);
        result.setResult("0");
        result.setMessage("操作完成");
        result.setImgUrl(user.getUserimg());
        return result;
    }

}
